<template>
    <div class="containers container">
        <div class="container top-return">
            <div class="inline-block">
                <el-page-header @back="goBack" :content="currentItem.title"></el-page-header>
            </div>
        </div>
        <div class="container spc">
            <el-form ref="formRef" :model="currentItem.rowData" :rules="rules" label-width="150px" class="demo-ruleForm">
                <!-- 商品信息 -->
                <div class="title head-title bottom-border">
                    账户信息
                </div>
                <el-row class="el-rows">
                    <el-col :span="12">
                        <el-form-item label="登录账号:" prop="account" style="margin-bottom: 0;">
                            <el-input v-model="currentItem.rowData!.account" placeholder="请输入登录账号"
                                :disabled="currentItem.title == '编辑'" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="登录密码:" :prop="currentItem.title == '新增' ? 'password' : ''"
                            style="margin-bottom: 0;">
                            <el-input v-model="currentItem.rowData!.password" placeholder="请输入登录密码" show-password
                                :disabled="currentItem.title == '编辑'" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <div class="title head-title bottom-border">
                    企业信息
                </div>
                <el-row class="el-rows">
                    <el-col :span="8">
                        <el-form-item label="经销商名称:" prop="carrierName" style="margin-bottom: 0;">
                            <el-input v-model="currentItem.rowData!.carrierName" placeholder="请输入经销商名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="负责人:" prop="director" style="margin-bottom: 0;">
                            <el-input v-model="currentItem.rowData!.director" placeholder="请输入负责人" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="电话:" prop="phone" style="margin-bottom: 0;">
                            <el-input v-model="currentItem.rowData!.phone" placeholder="请输入电话" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row class="el-rows">
                    <el-col :span="8">
                        <el-form-item label="门店地址:" prop="storeAddress" style="margin-bottom: 0;">
                            <el-input v-model="currentItem.rowData!.storeAddress" placeholder="请输入门店地址" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="所属机构:" prop="belong" style="margin-bottom: 0;">
                            <MySelect v-model="currentItem.rowData.belong" :request-api="listDealerManage"
                                placeholder="请选择所属机构" :fieldNames="memberFiled" :data="currentItem"
                                :initParam="{ pageNum: 1, pageSize: 99999, status: 0 }" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="状态" prop="status">
                            <el-radio-group v-model="currentItem.rowData.status">
                                <el-radio :key="0" :label="0" :value="0">启用</el-radio>
                                <el-radio :key="1" :label="1" :value="1">禁用</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>

                <div class="title head-title bottom-border">
                    权限配置 授权销售系列
                </div>
                <!-- 新增可选/已选系列组件 -->
                <el-row class="series-container">
                    <el-col :span="10">
                        <el-card title="可选系列" class="series-card">
                            <span style="font-weight: bold;">可选系列</span>
                            <el-scrollbar height="320px">
                                <div v-for="(series, index) in availableSeries" class="series-item"
                                    @click="handleSelect(series, index)">
                                    {{ series.name }}
                                </div>
                            </el-scrollbar>
                        </el-card>
                    </el-col>

                    <el-col :span="10">
                        <el-card title="已选系列" class="series-card">
                            <span style="font-weight: bold;">已选系列</span>
                            <el-scrollbar height="320px">
                                <div v-for="(series, index) in selectedSeries" class="series-item"
                                    @click="handleRemove(series, index)">
                                    {{ series.name }}
                                    <el-icon class="remove-icon">
                                        <Delete />
                                    </el-icon>
                                </div>
                            </el-scrollbar>
                        </el-card>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <div class="bot-pos-submit">
            <el-button class="simple-btn" @click="goBack">关闭</el-button>
            <el-button class="standard-btn" v-if="currentType != '查看'" @click="submitForm">提交</el-button>
        </div>

        <MyDiolg ref="dialogRef" />
    </div>
</template>
<script setup lang="ts">
import { ref, reactive, getCurrentInstance, toRefs, defineProps, onMounted, nextTick } from "vue";
import {
    CirclePlus,
    Delete,
    EditPen,
    Download,
    Upload,
    View,
    Refresh,
} from "@element-plus/icons-vue";
import {
    listDealerManage,
} from "@/api/system/dealerManage";
import {
    listWithFather
} from "@/api/zc/classification";
// import MyDiolg from "./Form.vue";
import { ElMessage } from "element-plus";
let memberFiled = { label: "dealerName", value: "id", labelName: "dealerName", autoLable: false };
const activeName = ref('first')
const dialogRef = ref(null);
const handleClick = (tab: any, event: Event) => {
    console.log(tab, event)
}
const formRef = ref();
const emit = defineEmits(["changeItem"]);
interface Props {
    currentItem: any;
    currentType: string;
}
const goBack = () => {
    emit("changeItem", "0");
};

// 接受父组件参数，配置默认值
const props = withDefaults(defineProps<Props>(), {
    currentItem: {
        rowData: {},
        api: null,
    },
    currentType: "",
});
//提交
const submitForm = async () => {
    formRef.value!.validate(async (valid) => {
        if (!valid) return;
        try {
            if (selectedSeries.value.length == 0) {
                ElMessage.error({ message: '请选择销售系列！' });
                return;
            } else {
                props.currentItem.rowData.optionalSeries = selectedSeries.value.map(item => item.name).join(",");
            }
            await props.currentItem.api({
                ...props.currentItem.rowData
            });
            ElMessage.success({ message: `${props.currentType}成功！` });
            goBack();
        } catch (error) {
            console.log(error);
        }
    });
};
const dialogCallBack = (data: any, index: number | null) => {
    console.log("回调", data);
    console.log("index", index);
    // 修改点：判断 index 是否为非 null（包括 0 等数字情况）
    if (index !== null) {
        props.currentItem.rowData.zcSupplierCertList[index] = data;
    } else {
        props.currentItem.rowData.zcSupplierCertList.push(data);
    }
};
const openDiolg = (title: string, row: any, index: number | null) => {
    const params = {
        title,
        isView: title === "查看",
        rowData: { ...row },
        api: title === "新增" ? dialogCallBack : title === "修改" ? dialogCallBack : undefined,
        index: index
        // getTableList: proTable.value?.getTableList,
    };
    dialogRef.value?.acceptParams(params);
};
// 表单验证规则（修改）
const rules = reactive({
    account: [  // 登录账号验证
        { required: true, message: '请输入登录账号', trigger: ['blur', 'change'] },
        { min: 3, max: 20, message: '账号长度在3-20个字符之间', trigger: ['blur', 'change'] }
    ],
    password: [  // 登录密码验证
        { required: true, message: '请输入登录密码', trigger: ['blur', 'change'] },
        { min: 6, max: 20, message: '密码长度在6-20个字符之间', trigger: ['blur', 'change'] }
    ],
    carrierName: [  // 经销商名称验证
        { required: true, message: '请输入经销商名称', trigger: ['blur', 'change'] }
    ],
    director: [  // 负责人验证
        { required: true, message: '请输入负责人', trigger: ['blur', 'change'] }
    ],
    phone: [  // 电话验证（手机号格式）
        { required: true, message: '请输入联系电话', trigger: ['blur', 'change'] },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的11位手机号', trigger: ['blur', 'change'] }
    ],
    storeAddress: [  // 门店地址验证
        { required: true, message: '请输入门店地址', trigger: ['blur', 'change'] }
    ],
    belong: [  // 所属机构验证
        { required: true, message: '请选择所属机构', trigger: ['blur', 'change'] }
    ],
    status: [  // 状态验证
        { required: true, message: '请选择状态', trigger: ['change'] }
    ]
});
const availableSeries = ref([]);
const selectedSeries = ref([]);
// 初始化系列数据（使用模拟数据）
const initSeriesData = async () => {
    // 模拟可选系列数据（可根据需要调整）
    const mockAvailableSeries = [
        { name: '奢华印象', id: 1 },
        { name: '经典系列', id: 2 },
        { name: '现代简约', id: 3 },
        { name: '轻奢风尚', id: 4 },
        { name: '普通质感', id: 5 },
    ];
    let { data } = await listWithFather({ fatherName: "产品系列" })
    if (props.currentType === '新增') {
        // props.currentItem.rowData.availableSeries = data.map((item: any) => { return { name: item.childName, id: item.id } });
        availableSeries.value = data.map((item: any) => { return { name: item.childName, id: item.id } });
    } else {
        // 编辑状态：
        let selectedWithId = []
        // 1. 将已选系列转换为带id的对象数组（假设原已选存储的是名称，需匹配id）
        if (props.currentItem.rowData.optionalSeries.length > 0) {
             selectedWithId = props.currentItem.rowData.selectedSeries.map((item: any, index: number) => {
                let obj = data.find((item2: any) => item2.childName === item);
                if (obj) {
                    return { name: obj.childName, id: obj.id }
                }
                // else{
                //     return { name: item, id: index }
                // }

            });
        }


        // 2. 从可选系列中过滤掉已选
        const availableFiltered = data.filter((item: any) => !selectedWithId.some((selected: any) => selected.id === item.id));

        console.log("selectedWithId", selectedWithId)

        const arr = availableFiltered.map((item: any) => ({
            name: item.childName,
            id: item.id
        }));

        // 分批添加逻辑（每批添加5个，可根据需求调整）
        const batchSize = 5; // 每批数量
        availableSeries.value = []; // 清空原数据

        // 分批处理
        for (let i = 0; i < arr.length; i += batchSize) {
            const batch = arr.slice(i, i + batchSize);
            availableSeries.value.push(...batch); // 批量添加当前批次
            await nextTick(); // 等待DOM更新
        }
        console.log("availableFiltered", availableSeries.value)
        // props.currentItem.rowData.selectedSeries = [...selectedWithId];
        selectedSeries.value = [...selectedWithId];

    }
};

// 处理选中系列
const handleSelect = (series, index) => {
    const newAvailable = [...availableSeries.value];
    const newSelected = [...selectedSeries.value];

    // 从可选移动到已选
    const [movedItem] = newAvailable.splice(index, 1);
    newSelected.push(movedItem);

    // 使用 Vue.set 确保响应性
    availableSeries.value = newAvailable;
    selectedSeries.value = newSelected;
};

// 处理移除系列
// const handleRemove = (series, index) => {
//     const newAvailable = [...availableSeries.value];
//     const newSelected = [...selectedSeries.value];

//     // 从已选移动到可选
//     const [movedItem] = newSelected.splice(index, 1);
//     newAvailable.push(movedItem);

//     // 使用 Vue.set 确保响应性
//     // availableSeries.value = newAvailable;
//     availableSeries.value.push(series);
//     selectedSeries.value = newSelected;
//     console.log("availableSeries", availableSeries.value)
// };

const handleRemove = (series, index) => {
    // 1. 复制当前已选和可选数组（创建新引用）
    const newSelected = selectedSeries.value.filter((_, i) => i !== index); // 移除目标项
    const newAvailable = [...availableSeries.value, series]; // 将移除项添加到可选数组

    // 2. 替换为新数组（强制触发响应式更新）
    availableSeries.value = newAvailable; // 关键：替换可选数组引用
    selectedSeries.value = newSelected;   // 替换已选数组引用
};

onMounted(() => {
    // if (props.currentType === '编辑') {
    //     initSeriesData();
    // }
    initSeriesData();
});
</script>
<style lang="scss" scoped>
.bot-pos-submit {
    position: fixed;
    height: 60px;
    background: white;
    width: calc(100vw - 252px);
    bottom: 0px;
    text-align: center;
    line-height: 60px;
    z-index: 999;
}

/* 卡片容器样式 */
// .el-rows {
//     display: flex;
//     flex-wrap: wrap;
//     margin: -10px;
// }

// .el-col {
//     padding: 10px;
// }

/* 卡片样式 */
.my-card {
    display: flex;
    border: 1px solid #ebeef5;
    border-radius: 8px;
    padding: 15px;
    background-color: #fff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
    height: 100%;
}

.my-card:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    transform: translateY(-3px);

}

.left-img {
    flex-shrink: 0;
    margin-right: 15px;
}

.left-img img {
    width: 60px;
    height: 60px;
    border-radius: 4px;
    object-fit: cover;
}

.right-info {
    flex-grow: 1;
}

.right-info-title {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 8px;
}

.right-info-title-left {
    display: flex;
    flex-direction: column;
}

.right-info-title-left span:first-child {
    font-weight: 600;
    font-size: 14px;
    color: #303133;
    margin-bottom: 4px;
}

.right-info-title-left span:last-child {
    font-size: 12px;
    color: #909399;
}

.card-actions {
    display: flex;
    align-items: center;
}

.card-actions .el-button {
    padding: 4px;
    margin-left: 5px;
    font-size: 16px;
}

.series-container {
    padding: 20px 16px; // 增加左右内边距
    gap: 32px; // 增大两栏间距
    justify-content: center; // 内容居中
}

.series-card {
    // height: 320px; // 稍微增加高度
    border: 1px solid #f0f2f5; // 浅边框
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); // 轻微阴影

    .el-card__header {
        padding: 12px 16px; // 调整标题内边距
        background: #f8f9fa; // 标题背景色
        border-bottom: 1px solid #f0f2f5; // 标题底边框
    }

    .el-card__title {
        font-size: 14px;
        color: #303133;
        font-weight: 600; // 标题加粗
    }

    .el-card__body {
        padding: 8px 0; // 内容区上下内边距
        height: 260px; // 内容区高度
    }
}

.series-item {
    padding: 8px 16px; // 调整项内边距
    margin: 4px 8px; // 增加项间距
    border-radius: 4px; // 项圆角
    font-size: 14px;
    color: #606266;
    transition: all 0.2s;

    &:hover {
        background: #e6f4ff; // 悬停背景色（蓝色系更突出交互）
        transform: translateX(4px); // 轻微右移反馈
    }
}

.remove-icon {
    color: #909399;
    font-size: 14px;
    margin-left: 12px;
    transition: color 0.2s;

    &:hover {
        color: #f56c6c; // 悬停红色反馈
    }
}

// 自定义滚动条样式
.el-scrollbar__wrap {
    overflow-x: hidden; // 隐藏水平滚动条
}

.el-scrollbar__thumb {
    background: #d9d9d9; // 滚动条颜色

    &:hover {
        background: #bfbfbf;
    }
}
</style>